package com.distribute.portal.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.distribute.common.pojo.DistributeResult;
import com.distribute.common.util.CookieUtils;
import com.distribute.common.util.HttpClientUtil;
import com.distribute.common.util.JsonUtils;
import com.distribute.pojo.ColumnData;
import com.distribute.pojo.DbItem;
import com.distribute.pojo.DbUser;
import com.distribute.portal.dao.JedisClient;
import com.distribute.portal.dao.impl.JedisClientCluster;
import com.distribute.portal.pojo.CollectionItem;
import com.distribute.portal.service.CollectionService;

import redis.clients.jedis.Tuple;
@Service
public class CollectionServiceImpl implements CollectionService {

	@Autowired
	JedisClient jedisClient;
	// rest服务基础url
	@Value("${REST_BASE_URL}")
	private String REST_BASE_URL;
	// 商品基本信息服务url
	@Value("${ITME_INFO_URL}")
	private String ITME_INFO_URL;
	@Value("${REDIS_USER_SESSION_KEY}")
	private String REDIS_USER_SESSION_KEY;
	@Value("${REDIS_USER_COLLECTION_KEY}")
	private String REDIS_USER_COLLECTION_KEY;
	@Value("${REDIS_COLLECTION_COUNT_KEY}")
	private String REDIS_COLLECTION_COUNT_KEY;

	// 获取收藏夹
	@Override
	public List<CollectionItem> getCollectionItemList(HttpServletRequest request, HttpServletResponse response) {
		List<CollectionItem> itemList = getCollectionItemList(request);
		return itemList;
	}

	private String getCollectionKey(HttpServletRequest request) {
		// 不能用car+uuid因为每次登陆uuid是会变化的所以用不变的就是username
		String userinfo = jedisClient
				.get(REDIS_USER_SESSION_KEY + ":" + CookieUtils.getCookieValue(request, "TT_TOKEN", true));
		if(userinfo!=null&&userinfo.length()>0){
			// 获取用户的名字
			String key = "collection-" + JsonUtils.jsonToPojo(userinfo, DbUser.class).getUsername();
			return key;
		}
		return "";
		
	}

	// 获取收藏夹的私有方法，作为内部调用
	private List<CollectionItem> getCollectionItemList(HttpServletRequest request) {
		String key = getCollectionKey(request);
		// 从redis中取商品列表
		// 判断是否存在收藏夹
		String collectionJson = jedisClient.hget(REDIS_USER_COLLECTION_KEY, key);
		if (collectionJson == null) {
			return new ArrayList<>();
		}
		// 把json转换成商品列表
		try {
			List<CollectionItem> list = JsonUtils.jsonToList(collectionJson, CollectionItem.class);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ArrayList<>();
	}

	/**
	 * 宠物收藏逻辑：添加收藏时获取用户username作为收藏夹（hash结构）的key ，然后根据宠物id获取宠物信息，将该宠物信息存入收藏夹中，key为开始获取的key。收藏夹是否存在该宠物在前端页面中
	 * 已进行逻辑判断
	 */
	@Override
	public DistributeResult addCollectionItem(Long itemId, HttpServletRequest request, HttpServletResponse response) {
		String key = getCollectionKey(request);
		// 取收藏夹商品列表
		List<CollectionItem> itemList = getCollectionItemList(request);
		CollectionItem collectionItem = new CollectionItem();
		// 根据商品id查询商品基本信息。
		String json = HttpClientUtil.doGet(REST_BASE_URL + ITME_INFO_URL + itemId);
		// 把json转换成java对象
		DistributeResult distributeResult = DistributeResult.formatToPojo(json, DbItem.class);
		if (distributeResult.getStatus() == 200) {
			DbItem item = (DbItem) distributeResult.getData();
			collectionItem.setId(item.getId());
			collectionItem.setTitle(item.getTitle());
			collectionItem.setName(item.getName());
			collectionItem.setAge(item.getAge());
			collectionItem.setSex(item.getSex());
			collectionItem.setImage(item.getImage() == null ? "" : item.getImage().split(",")[0]);
		}
		// 添加到收藏夹
		itemList.add(collectionItem);
		jedisClient.hset(REDIS_USER_COLLECTION_KEY, key, JsonUtils.objectToJson(itemList));
		//当 key 不存在，或 member 不是 key 的成员时， ZINCRBY key increment member 等同于 ZADD key increment member 。
		//当前商品收藏数+1
		jedisClient.zincrby(REDIS_COLLECTION_COUNT_KEY, 1, collectionItem.getId()+"");
		return DistributeResult.ok();
	}

	@Override
	public DistributeResult deleteCollectionItem(Long itemId, HttpServletRequest request,
			HttpServletResponse response) {
		String key = getCollectionKey(request);
		List<CollectionItem> itemList = getCollectionItemList(request);
		//从列表中找到此商品
		for (CollectionItem collectionItem : itemList) {
			if (collectionItem.getId() == itemId) {
				itemList.remove(collectionItem);
				break;
			}
				 
		}
		jedisClient.hset(REDIS_USER_COLLECTION_KEY, key, JsonUtils.objectToJson(itemList));
		//当 key 不存在，或 member 不是 key 的成员时， ZINCRBY key increment member 等同于 ZADD key increment member 。
		//当前商品收藏数-1
		jedisClient.zincrby(REDIS_COLLECTION_COUNT_KEY, -1, itemId+"");
		return DistributeResult.ok();
	}

	//判断收藏夹中是否存在该宠物，即判断宠物是否已经收藏
	@Override
	public boolean getCollectionItemById(Long itemId,HttpServletRequest request,HttpServletResponse response) {
		for(CollectionItem item : getCollectionItemList(request)) {
			if(item.getId()==itemId) {
				return true;
			}
		}
		return false;
	}

	@Override
	public List<ColumnData> getCollectionRevRange(long start, long end) {
		Set<Tuple> set = jedisClient.zrevrangeWithScores(REDIS_COLLECTION_COUNT_KEY, start, end);
		List<ColumnData> result = new ArrayList<ColumnData>();
		for (Tuple tuple : set) {
			ColumnData data = new ColumnData();
			data.setName(tuple.getElement());;
			data.setValue((long) tuple.getScore());
			result.add(data);
		}
		return result;
	}

}
